<template>
  <div class="layout-padding-auto">
    <el-form :model="state.queryForm" ref="queryRef" :inline="true">
      <el-form-item :label="$t('inputoutput.inputDate')" prop="inputDate">
        <div class="block">
          <el-date-picker v-model="inputDate" clearable type="daterange" unlink-panels range-separator="To"
                          start-placeholder="Start date" end-placeholder="End date" :shortcuts="shortcuts" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="query">{{ $t('so.query') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('so.reset') }}</el-button>
        <el-button type="success" icon="Download" plain @click="exportCard">{{ $t('inputOutputDetal.daochu') }}</el-button>
      </el-form-item>
<!--      <br />-->
<!--      <div style="margin: -5px 0  10px 0">-->
<!--        <span style="font-size: 14px;font-weight: 600;color: #303133">{{$t('inputOutputDetal.qtySum')}}：{{ totalQty||0 }}</span>-->
<!--      </div>-->
    </el-form>
    <el-table v-loading="loading" :data="tableData" border style="width: 100%; height: 100%" :cell-style="tableStyle.cellStyle" stripe :header-cell-style="tableStyle.headerCellStyle" ref="tableRef" show-summary :summary-method="getSummaries">
      <el-table-column prop="date" :label="$t('inputoutput.inputDate')" fixed width="120" align="center"/>
      <el-table-column v-for="process in processCodeOptions" :key="process.processCode" :label="process.processCode">
<!--        <el-table-column :property="`${process.processCode}.qualified`" :label="$t('inputOutputDetal.qualified')" align="center" width="120">-->
<!--          <template #default="scope">-->
<!--            <el-tag type="success">-->
<!--              {{ scope.row.inputData.find(item => item.processCode === process.processCode)?.qualified ?? '-' }}-->
<!--            </el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :property="`${process.processCode}.defective`" :label="$t('inputOutputDetal.defective')" align="center" width="120">-->
<!--          <template #default="scope">-->
<!--            <el-tag type="danger">-->
<!--              {{ scope.row.inputData.find(item => item.processCode === process.processCode)?.defective ?? '-' }}-->
<!--            </el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :property="`${process.processCode}.rate`" :label="$t('inputOutputDetal.rate')" align="center" width="120">-->
<!--          <template #default="scope">-->
<!--            {{ scope.row.inputData.find(item => item.processCode === process.processCode)?.rate ?? '-' }}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column :property="`${process.processCode}.qty`" :label="$t('inputoutput.qty')" align="center" >
          <template #default="scope">
            <el-tag type="success">
            {{ scope.row.inputData.find(item => item.processCode === process.processCode)?.qty || '--' }}
            </el-tag>
          </template>
        </el-table-column>

      </el-table-column>
    </el-table>
    <pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" v-bind="state.pagination" />
  </div>
</template>
<script setup lang="ts">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useI18n } from 'vue-i18n';
import {GetInputRecordSum, GetInputRecordSumTotalQty} from '/@/api/platform/report/inputoutput';
import {ElMessage} from "element-plus";



const { t } = useI18n();

const getYMD = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const today = new Date();
const endDate = new Date(today);
endDate.setDate(today.getDate());
today.setDate(today.getDate());
const inputDate = ref<[Date, Date] | null>([endDate, today]);
const queryRef = ref();
const tableRef = ref();
const totalQty = ref();
const totalQualifiedQty = ref()
const loading = ref(false);
const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 定义数据类型
interface ProcessData {
  processCode: string;
  // qualified: number;
  // defective: number;
  qty: string;
}

interface TableRowData {
  date: string;
  inputData: ProcessData[];
}

// 表格数据
const tableData = ref<TableRowData[]>([]);
// 工序选项
const processCodeOptions = ref<Array<{ processCode: string }>>([]);
// 合计行数据
const totalRow = ref<Record<string, ProcessData>>({});
// 合计
const sumTotalList  = ref<any[]>([])

const state = reactive<BasicTableProps>({
  queryForm: {
    StartDate: inputDate.value ? getYMD(inputDate.value[0]) : '',
    EndDate: inputDate.value ? getYMD(inputDate.value[1]) : '',
  },
  pageList: GetInputRecordSum,
  pagination: {
    total: 0,
    current: 1,
    pageSize: 20
  }
});

// 计算合计数据的方法
const calculateTotal = (data: TableRowData[]) => {
  // 初始化合计对象，为每个工序创建初始值
  const total: Record<string, ProcessData> = {};
  processCodeOptions.value.forEach(({ processCode }) => {
    total[processCode] = {
      processCode,
      qty: 0,
      // defective: 0,
      // rate: '0%'
    };
  });

  // 遍历数据，累加每个工序的合格和不合格数量
  data.forEach(row => {
    row.inputData.forEach(item => {
      const processTotal = total[item.processCode];
      if (processTotal) {
        processTotal.qty += Number(item.qty);
        // processTotal.defective += Number(item.defective);
      }
    });
  });

  // // 计算每个工序的合格率
  // Object.values(total).forEach(processTotal => {
  //   const totalPieces = processTotal.qualified + processTotal.defective;
  //   if (totalPieces > 0) {
  //     const rate = (processTotal.qualified / totalPieces) * 100;
  //     processTotal.rate = rate.toFixed(2) + '%';
  //   }
  // });

  return total;
};

// 表格合计行方法
const getSummaries = (param: { columns: any[] }) => {
  const { columns } = param;
  const sums: string[] = [];

  columns.forEach((column, index) => {
    // 第一列显示"合计"
    if (index === 0) {
      sums[index] = t('inputOutputDetal.total');
      return;
    }

    // 获取工序代码和列类型
    const [processCode, columnType] = (column.property || '').split('.');

    // 查找对应工序的数据
    const processData = sumTotalList.value.find(item => item.processCode === processCode);

    // 如果找不到对应的工序数据，显示'-'
    if (!processCode || !processData) {
      sums[index] = '-';
      return;
    }

    // 根据列类型返回对应的值
    // const processData = totalRow.value[processCode];
    // console.log(columnType,'columnType')
    switch (columnType) {

      case 'qty':
        sums[index] = processData.totalQty.toString();
        break;
      // case 'defective':
      //   sums[index] = processData.defective.toString();
      //   break;
      // case 'rate':
      //   sums[index] = processData.rate;
      //   break;
      default:
        sums[index] = '-';
    }
  });

  return sums;
};

// 初始化数据
onMounted(() => {
  query();
});

// 查询方法
const query = () => {
  state.queryForm.StartDate = inputDate.value?.length > 0 ? getYMD(inputDate.value[0]) : '';
  state.queryForm.EndDate = inputDate.value?.length > 0 ? getYMD(inputDate.value[1]) : '';


  if(state.queryForm.StartDate == '' || state.queryForm.EndDate == '') return   ElMessage({
    message: t('inputOutputDetal.timeMsg'),
    type: 'warning',
    plain: true,
  })

  loading.value = true;
  // 获取总数统计
  GetInputRecordSumTotalQty(state.queryForm).then((res) => {
    // totalQty.value = res.data.totalQty;
    sumTotalList.value = res.data;
  });


  // 获取表格数据
  GetInputRecordSum({
    ...state.queryForm,
    current: state.pagination.current,
    size: state.pagination.pageSize
  }).then((res) => {
    if (res.data?.records) {
      tableData.value = res.data.records;
      state.pagination.total = res.data.total || 0;

      // 从返回的数据中提取所有唯一的 processCode
      // const uniqueProcessCodes = new Set<string>();
      // tableData.value.forEach(row => {
      //   row.inputData.forEach(item => {
      //     uniqueProcessCodes.add(item.processCode);
      //   });
      // });
      //
      // // 更新工序选项
      // processCodeOptions.value = Array.from(uniqueProcessCodes).sort().map(code => ({
      //   processCode: code
      // }));

      const processCodeList: string[] = [];
      tableData.value.forEach(row => {
        row.inputData.forEach(item => {
          if (!processCodeList.includes(item.processCode)) {
            processCodeList.push(item.processCode);
          }
        });
      });

      processCodeOptions.value = processCodeList.map(code => ({ processCode: code }));


      // 计算合计数据
      totalRow.value = calculateTotal(tableData.value);

      loading.value = false;
    }
  }).catch(() => {
    loading.value = false;
  });
};

// 重置查询
const resetQuery = () => {
  inputDate.value = null;
  const now = new Date();
  const startDate = new Date(now.getFullYear(), now.getMonth(), 1); // 本月开始日期
  const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0); // 本月结束日期

  state.queryForm.StartDate = startDate.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD
  state.queryForm.EndDate = endDate.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD

  inputDate.value = [startDate,endDate];
  state.pagination.current = 1;
  query();
};

// 处理分页变化
const handleSizeChange = (val: number) => {
  state.pagination.current = 1;
  state.pagination.pageSize = val;
  query();
};

const handleCurrentChange = (val: number) => {
  state.pagination.current = val;
  query();
};

// 导出功能
const exportCard = () => {


  if (!inputDate.value || inputDate.value.length === 0)   return ElMessage({
    message: t('inputOutputDetal.timeMsg'),
    type: 'warning',
    plain: true,
  })
  downBlobFile('/report/inputOutput/ExportProductInput', {
    StartDate: inputDate.value?.length > 0 ? getYMD(inputDate.value[0]) : '',
    EndDate: inputDate.value?.length > 0 ? getYMD(inputDate.value[1]) : '',
  }, 'ProductInput.xlsx');
};

// 获取表格相关方法
const { tableStyle, downBlobFile } = useTable(state);
</script>
